﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;

namespace MonitorDaemon
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = Process.GetProcessesByName("w3wp");
            foreach(var p in list)
            {
                Console.WriteLine("\r\n-----------------------------------");
                Console.WriteLine("pid:{0},Name:{1}", p.Id, GetProcessUserName(p.Id));
                Test(p.Id);
            }
        }

        /// <summary>
        /// 通过进程Id来获取进程的用户名
        /// </summary>
        /// <param name="processId">进程Id</param>
        /// <returns></returns>
        private static string GetProcessUserName(int processId)
        {
            string name = "";

            SelectQuery query = new SelectQuery("select * from Win32_Process where processID=" + processId);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            try
            {
                foreach (ManagementObject disk in searcher.Get())
                {
                    ManagementBaseObject inPar = null;
                    ManagementBaseObject outPar = null;

                    inPar = disk.GetMethodParameters("GetOwner");

                    outPar = disk.InvokeMethod("GetOwner", inPar, null);

                    name = outPar["User"].ToString();
                    break;
                }
            }
            catch
            {
                name = "SYSTEM";
            }

            return name;
        }

        public static void Test(int processId)
        {
            try
            {
                var q = new SelectQuery("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process where IDProcess=" + processId);
                var searcher = new ManagementObjectSearcher(q);
                //ManagementObjectSearcher searcher =
                //    new ManagementObjectSearcher("root\\CIMV2",
                //    "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    //Console.WriteLine("-----------------------------------");
                    //Console.WriteLine("Name: {0}", queryObj["Name"]);
                    Console.WriteLine("PercentProcessorTime: {0}", queryObj["PercentProcessorTime"]);
                }
            }
            catch (ManagementException e)
            {
                Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}
